package model

import (
	"server/tool"
)

type User struct {
	BaseModel
	Account       string `gorm:"unique;comment:'账号'"`
	Password      string `gorm:"comment:'密码'"`
	Phone         string `gorm:"->:false;<-:create;unique;comment:'手机号码'"`
	NickName      string `gorm:"comment:'昵称'"`
	Avatar        string `gorm:"comment:'头像URL'"`
	Birthday      string `gorm:"comment:'出生日期'"`
	Sex           int    `gorm:"comment:'性别：0男 1女';default:0"`
	Email         string `gorm:"comment:'邮箱'"`
	RoleId        int    `gorm:"comment:'关联角色ID';default:0"`
	StoreId       int    `gorm:"comment:'关联店铺ID';default:0"`
	LastLoginIp   string `gorm:"comment:'最后登录IP'"`
	LastLoginTime int    `gorm:"comment:'最后登录时间';default:0"`
}

var user User
var users []User

func (e *User) GetByPass(model User) (User, error) {
	if err := GlobalDB.Where("account = ?", model.Account).Where("password = ?", model.Password).Where("status = ?", 1).First(&model).Error; err != nil {
		return model, err
	}
	return model, nil
}
func (e *User) GetList(param tool.Pagination) ([]User, error) {
	var result []User
	if param.KeyWords == "" {
		if err := GlobalDB.Limit(param.PageSize).Offset((param.PageNo - 1) * param.PageSize).
			Find(&users).Error; err != nil {
			return users, err
		}
	} else {
		if err := GlobalDB.Limit(param.PageSize).Offset((param.PageNo-1)*param.PageSize).Where("account like ?", "%"+param.KeyWords+"%").
			Find(&users).Error; err != nil {
			return users, err
		}
	}
	for _, info := range users {
		info.Avatar = tool.Config().Os.DoMain + info.Avatar
		result = append(result, info)
	}
	return result, nil
}
func (e *User) GetOne(id uint) (User, error) {
	if err := GlobalDB.Where("id = ?", id).First(&user).Error; err != nil {
		return user, err
	}
	return user, nil
}
func (e *User) Add(model User) error {
	if err := GlobalDB.Create(&model).Error; err != nil {
		return err
	}
	return nil
}
func (e *User) Edit(model User) error {
	if err := GlobalDB.Updates(&model).Error; err != nil {
		return err
	}
	return nil
}
func (e *User) Del(id uint) error {
	if err := GlobalDB.Delete(id).Error; err != nil {
		return err
	}
	return nil
}
func (e *User) ChangePass(id uint, password string) (User, error) {
	if err := GlobalDB.Where("id = ?", id).Where("password = ?", password).First(&user).Error; err != nil {
		return user, err
	}
	return user, nil
}
